// 定义一个全局的事件处理器存储对象
const ExamRoomHandlers = {
    listeners: new Map(),

    // 添加事件监听器并存储引用
    addListener(element, eventType, handler) {
        if (!element) return;

        const elementListeners = this.listeners.get(element) || new Map();
        const handlers = elementListeners.get(eventType) || new Set();

        handlers.add(handler);
        elementListeners.set(eventType, handlers);
        this.listeners.set(element, elementListeners);

        element.addEventListener(eventType, handler);
    },

    // 移除特定元素的所有事件监听器
    removeAllListeners(element) {
        if (!this.listeners.has(element)) return;

        const elementListeners = this.listeners.get(element);
        elementListeners.forEach((handlers, eventType) => {
            handlers.forEach(handler => {
                element.removeEventListener(eventType, handler);
            });
        });

        this.listeners.delete(element);
    },

    // 清理所有事件监听器
    cleanup() {
        this.listeners.forEach((elementListeners, element) => {
            this.removeAllListeners(element);
        });
        this.listeners.clear();
    }
};

// 主初始化函数
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否在考试房间编辑页面
    const isExamRoomPage = document.querySelector('form') &&
                          (document.getElementById('id_name') ||
                           document.getElementById('id_exam_type'));

    if (!isExamRoomPage) return;

    // 添加隐藏的状态字段，默认为"准备中"
    const form = document.querySelector('form');

    // 添加隐藏的状态字段
    if (form && !document.getElementById('id_status')) {
        const statusField = document.createElement('input');
        statusField.type = 'hidden';
        statusField.id = 'id_status';
        statusField.name = 'status';
        statusField.value = 'preparing';
        form.appendChild(statusField);
    }

    // 确保总分字段存在
    if (!document.getElementById('id_total_score')) {
        const totalScoreField = document.createElement('input');
        totalScoreField.type = 'text';
        totalScoreField.id = 'id_total_score';
        totalScoreField.name = 'total_score';
        totalScoreField.readOnly = true;
        totalScoreField.style.backgroundColor = '#f0f0f0';
        totalScoreField.style.cursor = 'not-allowed';

        const lastFieldset = form.querySelector('fieldset:last-of-type');
        if (lastFieldset) {
            lastFieldset.appendChild(totalScoreField);
            const label = document.createElement('label');
            label.htmlFor = 'id_total_score';
            label.textContent = '试卷总分：';
            lastFieldset.insertBefore(label, totalScoreField);
        } else {
            form.appendChild(totalScoreField);
        }
    }

    // 初始化科目选择字段
    const subjectFields = [
        {
            select: document.getElementById('id_subject_1'),
            statsDiv: createStatsDiv('subject_1_stats')
        },
        {
            select: document.getElementById('id_subject_2'),
            statsDiv: createStatsDiv('subject_2_stats')
        },
        {
            select: document.getElementById('id_subject_3'),
            statsDiv: createStatsDiv('subject_3_stats')
        }
    ];

    // 为每个科目选择字段添加事件监听器
    subjectFields.forEach(field => {
        if (field.select) {
            field.select.parentNode.appendChild(field.statsDiv);

            const handleSubjectChange = () => {
                updateSubjectStats(field.select.value, field.statsDiv);
            };

            ExamRoomHandlers.addListener(field.select, 'change', handleSubjectChange);

            if (field.select.value) {
                handleSubjectChange();
            }
        }
    });

    // 初始化题目数量和分值字段的监听器
    initScoreCalculation();
    updateTotalScore();
});

// 在页面即将卸载时清理事件监听器
window.addEventListener('pagehide', () => {
    ExamRoomHandlers.cleanup();
});

// 作为后备方案，也监听 beforeunload 事件
window.addEventListener('beforeunload', () => {
    ExamRoomHandlers.cleanup();
});

// 初始化分数计算功能
function initScoreCalculation() {
    const handleScoreUpdate = () => updateTotalScore();
    const handleInputValidation = (e) => {
        let value = e.target.value;
        value = value.replace(/[^\d.]/g, '');
        const parts = value.split('.');
        if (parts.length > 2) {
            value = parts[0] + '.' + parts.slice(1).join('');
        }
        if (value !== e.target.value) {
            e.target.value = value;
        }
        updateTotalScore();
    };
    // 获取所有需要监听的输入字段
    const fields = [
        'id_single_choice_count', 'id_single_choice_score',
        'id_multiple_choice_count', 'id_multiple_choice_score',
        'id_judgment_count', 'id_judgment_score'
    ];

    // 检查哪些字段存在
    const existingFields = [];
    const missingFields = [];

    fields.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            existingFields.push({id: id, element: element});
        } else {
            missingFields.push(id);
        }
    });

    // 打印调试信息
    // console.log('Fields found:', existingFields.map(f => f.id));

    if (missingFields.length > 0) {
        // console.log('Missing fields:', missingFields);
    }

    // 如果没有任何字段，则退出
    if (existingFields.length === 0) {
        // console.log('没有找到任何相关字段，跳过初始化分数计算功能');
        return;
    }

    // 为每个输入字段添加事件监听器
    existingFields.forEach(field => {
        ['input', 'change', 'blur'].forEach(eventType => {
            ExamRoomHandlers.addListener(field.element, eventType, handleScoreUpdate);
        });

        // 添加值验证
        ExamRoomHandlers.addListener(field.element, 'input', handleInputValidation);
    });

    // 初始计算总分
    updateTotalScore();

    // 确保总分字段存在并设置为只读
    const totalScoreField = document.getElementById('id_total_score');
    if (totalScoreField) {
        totalScoreField.readOnly = true;
        totalScoreField.style.backgroundColor = '#f0f0f0';
        totalScoreField.style.cursor = 'not-allowed';

        // 添加清晰的视觉提示
        totalScoreField.style.border = '2px solid #ccc';
        totalScoreField.style.padding = '5px';
        totalScoreField.style.borderRadius = '4px';
    } else {
        // console.log('未找到总分字段，请检查字段是否正确创建');
    }
}

// 更新总分
function updateTotalScore() {
    // 首先检查是否存在所需字段
    const fieldPairs = [
        ['id_single_choice_count', 'id_single_choice_score'],
        ['id_multiple_choice_count', 'id_multiple_choice_score'],
        ['id_judgment_count', 'id_judgment_score']
    ];

    let totalScore = 0;
    let hasValidFields = false;
    let calculationDetails = [];

    // 计算每对字段的得分
    fieldPairs.forEach(pair => {
        const countElement = document.getElementById(pair[0]);
        const scoreElement = document.getElementById(pair[1]);

        if (countElement && scoreElement) {
            // 严格的数值验证
            let count = countElement.value.trim();
            let score = scoreElement.value.trim();

            // 验证并转换数值
            count = /^\d*\.?\d*$/.test(count) ? parseFloat(count) : 0;
            score = /^\d*\.?\d*$/.test(score) ? parseFloat(score) : 0;

            // 确保是有效数字
            count = isNaN(count) ? 0 : count;
            score = isNaN(score) ? 0 : score;

            const subtotal = count * score;
            totalScore += subtotal;
            hasValidFields = true;

            // 记录计算细节用于调试
            calculationDetails.push(`${pair[0]}: ${count} × ${score} = ${subtotal}`);
        }
    });

    // 如果没有有效字段，则退出
    if (!hasValidFields) {
        // console.log('没有有效的分数字段，跳过总分计算');
        return;
    }

    // 输出计算细节到控制台
    // console.log('分数计算明细:', calculationDetails.join(', '));
    // console.log('总分:', totalScore);

    // 更新总分字段
    const totalScoreField = document.getElementById('id_total_score');
    if (totalScoreField) {
        const oldValue = totalScoreField.value;
        const newValue = totalScore.toFixed(2);  // 保留两位小数

        // 只在值真正改变时更新
        if (oldValue !== newValue) {
            totalScoreField.value = newValue;

            // 触发change事件，确保其他可能依赖于总分的逻辑能够执行
            const changeEvent = new Event('change', { bubbles: true });
            totalScoreField.dispatchEvent(changeEvent);

            // 触发input事件
            const inputEvent = new Event('input', { bubbles: true });
            totalScoreField.dispatchEvent(inputEvent);

            // 可视化反馈，让用户知道总分已更新
            totalScoreField.style.transition = 'background-color 0.3s';
            totalScoreField.style.backgroundColor = '#e8f0fe';
            setTimeout(() => {
                totalScoreField.style.backgroundColor = '#f0f0f0';
            }, 300);
        }
    } else {
        console.error('未找到总分字段，无法更新总分');
    }
}

function createStatsDiv(id) {
    const div = document.createElement('div');
    div.id = id;
    div.className = 'subject-stats';
    return div;
}

function updateSubjectStats(subjectId, statsDiv) {
    if (!subjectId) {
        statsDiv.innerHTML = '';
        return;
    }

    // 获取CSRF令牌
    const csrfTokenElement = document.querySelector('[name=csrfmiddlewaretoken]');
    if (!csrfTokenElement) {
        statsDiv.innerHTML = '<div class="error-message">无法获取CSRF令牌</div>';
        return;
    }
    const csrftoken = csrfTokenElement.value;

    // 发起AJAX请求
    fetch(`/exam/api/subject/${subjectId}/stats/`, {
        method: 'GET',
        headers: {
            'X-CSRFToken': csrftoken,
            'Accept': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            const stats = data.data;
            statsDiv.innerHTML = `
                <h4>${stats.subject_name} 题库统计：</h4>
                <div class="stats-item">
                    <strong>单选：</strong>${stats.single_choice}道，
                    <strong>多选：</strong>${stats.multiple_choice}道，
                    <strong>判断：</strong>${stats.judge}道。
                </div>
            `;
        } else {
            statsDiv.innerHTML = `
                <div class="error-message">
                    获取题目统计信息失败：${data.message}
                </div>
            `;
        }
    })
    .catch(error => {
        statsDiv.innerHTML = `
            <div class="error-message">
                获取题目统计信息时发生错误：${error.message}
            </div>
        `;
    });
}